class Solution {
public:
    int dx[4]={0,0,1,-1};
    int dy[4]={1,-1,0,0};
    int orangesRotting(vector<vector<int>>& grid) {
        int szx = grid.size();
        int szy = grid[0].size();
        vector<vector<bool>> vis(szx,vector<bool>(szy,false));
        queue<pair<int,int>> q;
        int sum = 0;
        bool xinxian = false;
        for(int i=0;i<szx;i++){
            for(int j=0;j<szy;j++){
                if(grid[i][j]==2){
                    sum++;
                    q.push({i,j});
                    vis[i][j]=true;
                }if(grid[i][j]==1){
                    xinxian = true;
                }
            }
        }
        if(!xinxian&&!sum) return 0;
        int sump=0;
        int ans=0;
        while(!q.empty()){
            auto t = q.front();
            q.pop();
            int x=t.first;
            int y=t.second;
            for(int i=0;i<4;i++){
                int x1=x+dx[i];
                int y1=y+dy[i];
                if(x1>=0&&x1<szx&&y1>=0&&y1<szy&&!vis[x1][y1]&&grid[x1][y1]==1){
                    q.push({x1,y1});
                    grid[x1][y1]=2;
                    vis[x1][y1]=true;
                    sump++;
                }
            }
            sum--;
            if(sum==0){
                ans++;
                sum=sump;
                sump=0;
            }
        }
        for(int i=0;i<szx;i++){
            for(int j=0;j<szy;j++){
                if(grid[i][j]==1){
                    return -1;
                }
            }
        }
        return ans-1;
    }
};